import xmindparser
import re


class Analyzer:
    """分析器基类，定义分析接口"""

    def analyze(self, content: str):
        raise NotImplementedError("子类必须实现analyze方法")


class TitleTopicAnalyzer(Analyzer):
    """具体分析器：统计title与topics的数量差"""

    def __init__(self):
        # 预编译正则表达式提升效率
        self.title_pattern = re.compile(r"title\w*")
        self.topics_pattern = re.compile(r"topics\w*")

    def analyze(self, content: str) -> int:
        """执行正则匹配并返回计算结果"""
        title_count = len(self.title_pattern.findall(content))
        topics_count = len(self.topics_pattern.findall(content))
        return title_count - topics_count - 1


class XmindTools:
    def __init__(self, file, analyzer: Analyzer):
        self.file = file
        self.analyzer = analyzer
        self._content_cache = None  # 解析结果缓存

    def _parse_xmind(self) -> str:
        """实际解析方法，带缓存机制"""
        if self._content_cache is None:
            content_dict = xmindparser.xmind_to_dict(self.file)
            self._content_cache = str(content_dict)
        return self._content_cache

    def get_result(self) -> int:
        """获取分析结果"""
        content_str = self._parse_xmind()
        return self.analyzer.analyze(content_str)


if __name__ == "__main__":
    # 使用示例
    analyzer = TitleTopicAnalyzer()
    tool = XmindTools(r"D:\work\纳税申报\6月紧急版.xmind", analyzer)
    print(tool.get_result())
